/**
 * @file lv_log_file.c
 * @brief Implementation of LVGL log to file functionality
 */

/*********************
 *      INCLUDES
 *********************/
#include "lv_log.h"
#include <stdio.h>
#include <time.h>

#if LV_USE_LOG

/*********************
 *      DEFINES
 *********************/
#define LOG_FILE_PATH "lvgl.log"

/**********************
 *  STATIC VARIABLES
 **********************/
static FILE* log_file = NULL;

/**********************
 *   STATIC FUNCTIONS
 **********************/
static void log_to_file(const char* buf)
{
    if (log_file == NULL) {
        log_file = fopen(LOG_FILE_PATH, "a");
        if (log_file == NULL) return;
        
        /* Add timestamp when opening the log file */
        time_t now;
        time(&now);
        fprintf(log_file, "\n\n=== Log started at: %s", ctime(&now));
    }
    
    fprintf(log_file, "%s", buf);
    fflush(log_file);
}

/**********************
 *   GLOBAL FUNCTIONS
 **********************/

/**
 * Initialize the log-to-file functionality
 */
void lv_log_file_init(void)
{
    char buf[100];
    fprintf(buf,"lvgl log init ，log level is %d\n",LV_LOG_LEVEL);
    log_to_file(buf);
    lv_log_register_print_cb(log_to_file);
}

/**
 * Close the log file
 */
void lv_log_file_close(void)
{
    if (log_file) {
        /* Add timestamp when closing the log file */
        time_t now;
        time(&now);
        fprintf(log_file, "\n=== Log ended at: %s\n", ctime(&now));
        
        fclose(log_file);
        log_file = NULL;
    }
}

#endif /*LV_USE_LOG*/